package 剑指offer;

import java.util.Stack;

/**
 * @description:
 * @author: ywk
 * @date: 2021-06-05
 */
public class 补全中序表达式左括号 {
    public static void main(String[] args) {
        System.out.println(appStr("(1 + 2 ) * (3 - 4) ) * (5 - 6 ) )"));
    }

    public static String appStr(String s) {
        Stack<String> numStack = new Stack();
        Stack<Character> opStack = new Stack();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                continue;
            } else if ('0' <= c && c < '9') {
                numStack.push(c + "");
            } else {
                if (c == ')') {
                    String back = numStack.pop();
                    String pre = numStack.pop();
                    Character op = opStack.pop();
                    if (!opStack.isEmpty() && opStack.peek() == '(') {
                        opStack.pop();
                    }
                    StringBuilder sb = new StringBuilder();
                    sb.append("(" + " ").append(pre + " ").append(op + " ").append(back + " ").append(")");
                    numStack.push(sb.toString());
                } else {
                    //*-+/ (
                    opStack.push(c);
                }
            }
        }
        return numStack.pop();
    }
}
